//
//  BuyViewController.m
//  预购清单
//
//  Created by  on 2022/10/16.
//

#import "BuyViewController.h"
#import "BuyMidView.h"
#import "BuyHeader.h"
#import "BuyTypeCell.h"
#import "PayTypeCell.h"
#import "TypeViewController.h"

@interface BuyViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (strong, nonatomic) NSArray *array;
@property (strong, nonatomic) NSMutableArray <PrepayType *> *typeArray;
@property (assign, nonatomic) NSInteger select;
@property (assign, nonatomic) NSInteger selectType;
@property (strong, nonatomic) Prepay *model;
@end

@implementation BuyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self initUI];
    [self addNotify];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)initUI{
    self.title = LS(@"预购");
    self.array =@[@"支付宝",@"微信",@"银联",@"现金支付",@"信用卡"];
    self.select = self.array.count + 1;
    self.selectType = 100000;
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(-10, StuBarHight+5, 40, 34);
    [rightBtn addTarget:self action:@selector(actionForDone) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:LS(@"完成") forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = backItem;
    [self.collectionView registerNib:[PayTypeCell nib] forCellWithReuseIdentifier:[PayTypeCell ID]];
    [self.collectionView registerNib:[BuyTypeCell nib] forCellWithReuseIdentifier:[BuyTypeCell ID]];
    [self.collectionView registerNib:[BuyHeader nib] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[BuyHeader ID]];
    [self.collectionView registerNib:[BuyMidView nib] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[BuyMidView ID]];
    self.collectionView.c_top.equalTo(self.view.c_top).coffset(0);
    self.collectionView.c_left.equalTo(self.view.c_left).coffset(16);
    self.collectionView.c_right.equalTo(self.view.c_right).coffset(-16);
    self.collectionView.c_bottom.equalTo(self.view.c_bottom).coffset(0);
}
- (void)takePhoto{
    WS(self)
    SheetViewController *sheetvc = [SheetViewController new];
    sheetvc.withCancel = NO;
    sheetvc.array = @[@"拍摄",@"相册"];
    sheetvc.block = ^(int index, NSString * _Nonnull text) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [CCHud startHud];
        });
        UIImagePickerController *vc = [UIImagePickerController new];
        vc.delegate = weakself;
        vc.allowsEditing = YES;
        vc.sourceType = index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
        vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [[weakself currentVC] presentViewController:vc animated:YES completion:^{
            [CCHud stopHud];
        }];
    };
    [[weakself currentVC] presentViewController:sheetvc animated:NO completion:nil];
}
- (void)actionForDone{
    if (self.model.money <= 0) {
        return [CCHud msg:LS(@"金额不能为零")];
    }else if (self.model.img == nil || self.model.img.length <= 0){
        return [CCHud msg:LS(@"图片不能为空")];
    }else if (self.model.payType.length <= 0){
        return [CCHud msg:LS(@"请选择预支付方式")];
    }else if (self.model.descri.length <= 0){
        return [CCHud msg:LS(@"请输入备注")];
    }else if (self.model.type == nil){
        return [CCHud msg:LS(@"请选择类型")];
    }
    PickViewController *vc = [PickViewController new];
    vc.stamp = [[NSDate currentTimeStamp:@"yyyy-MM-dd HH:mm:ss"] intValue];
    vc.type = DateTypeday;
    vc.stampBlock = ^(NSInteger stamp) {
        [CCHud msg:LS(@"保存中")];
        self.model.stamp = stamp;
        [PrepayTool update:self.model complete:^(BOOL success) {
            [NotifyTool post:notifyPayUpdate :nil];
            [CCHud stopHud];
            [self backBtnAction];
        }];
    };
    [vc show];
}
- (void)loadData{
    [PrePayTypeTool find:APP.user.account complete:^(NSMutableArray<PrepayType *> * _Nonnull result) {
        self.typeArray = result;
        [self.collectionView reloadData];
    }];
}
- (Prepay *)model{
    if (!_model) {
        _model = [Prepay new];
        _model.account = APP.user.account;
    }
    return _model;
}
- (void)addNotify{
    [super addNotify];
    [NotifyTool add:self :@selector(loadData) :notifyPrepayTypeUpdate :nil];
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    self.model.img = UIImageJPEGRepresentation(img, 0.5);
    [self.collectionView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  section == 0 ? self.array.count : self.typeArray.count + 1;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        PayTypeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[PayTypeCell ID] forIndexPath:indexPath];
        cell.img.image = [UIImage imageNamed:self.array[indexPath.row]];
        cell.selectImg.hidden = self.select != indexPath.row;
        return  cell;
    }else{
        BuyTypeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[BuyTypeCell ID] forIndexPath:indexPath];
        cell.model = indexPath.row <= self.typeArray.count-1?self.typeArray[indexPath.row]:nil;
        cell.selectBtn.hidden = indexPath.row >= self.typeArray.count;
        cell.selectBtn.hidden = self.selectType != indexPath.row;
        return  cell;
    }
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        BuyHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[BuyHeader ID] forIndexPath:indexPath];
        header.model = self.model;
        header.block = ^{
            [self takePhoto];
        };
        return  header;
    }else{
        BuyMidView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[BuyMidView ID] forIndexPath:indexPath];
        header.model = self.model;
        return  header;
    }
}
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        self.select = indexPath.row;
        self.model.payType = self.array[indexPath.row];
        [collectionView reloadData];
    }else{
        if (indexPath.row <= self.typeArray.count-1) {
            self.selectType = indexPath.row;
            self.model.type = self.typeArray[indexPath.row];
            [collectionView reloadData];
        }else{
            TypeViewController *vc = [TypeViewController new];
            [self push:vc :YES];
        }
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return  (indexPath.section == 0) ? CGSizeMake(76,54):CGSizeMake(57,76);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(0, 16, 0, 16);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 16;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    CGFloat h = section == 0 ? 110 : 104;
    return CGSizeMake(SCREEN_WIDTH, h);
}

@end
